package com.goldgov.mobile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldgov.authorityInfo.service.AuthorityInfoInit;
import com.goldgov.conference.service.ConferenceAttendance;
import com.goldgov.conference.service.ConferenceQuery;
import com.goldgov.conference.service.ConferenceService;
import com.goldgov.conference.service.ConferenceUser;
import com.goldgov.distancelearning.service.Distancelearning;
import com.goldgov.distancelearning.service.DistancelearningAttendance;
import com.goldgov.distancelearning.service.DistancelearningBean;
import com.goldgov.distancelearning.service.DistancelearningCourse;
import com.goldgov.distancelearning.service.DistancelearningCourseQuery;
import com.goldgov.distancelearning.service.DistancelearningQuery;
import com.goldgov.distancelearning.service.DistancelearningService;
import com.goldgov.distancelearning.service.DistancelearningUser;
import com.goldgov.distancelearning.service.DistancelearningUserQuery;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.ms.adapter.call.RemoteCallService;
import com.goldgov.notice.service.NoticeQuery;
import com.goldgov.notice.service.NoticeService;
import com.goldgov.securityworkbench.attachment.AttachementBean;
import com.goldgov.utils.DataUtil;
import com.goldgov.utils.DateUtil;
import com.goldgov.utils.PrintUtil;
import com.goldgov.utils.PropertyUtil;
import com.goldgov.utils.UrlUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @ClassName: DistancelearningForMobileController
 * @Description: 远程教育移动接口
 * @author hanxiangyu
 * @date 2018年6月27日 上午11:04:36
 */

@RestController
@RequestMapping("/mobile/distancelearning")
@Api("远程教育移动接口")
public class DistancelearningForMobileController {

	@Autowired
	private DistancelearningService distancelearningService;

	@Autowired
	private NoticeService noticeService;

	@Autowired
	private RemoteCallService remoteCallService;

	@Autowired
	private ConferenceService conferenceService;
	
	/**
	 * 预新增
	 * 
	 * @date 2018年6月22日 下午4:32:32
	 * @author hanxiangyu
	 * @param request
	 * @return
	 */
	@GetMapping("/preAddDis")
	@ApiOperation(value = "预新增远程教育", notes = "查询返回远程教育ID")
	public JsonSuccessObject<Distancelearning> preAddConference(HttpServletRequest request) {
		Distancelearning obj = distancelearningService.preAdd();
		JsonSuccessObject<Distancelearning> returnResult = new JsonSuccessObject<Distancelearning>(obj);
		return returnResult;
	}

	/**
	 * 查询远程教育
	 * 
	 * @date 2018年6月22日 下午4:33:00
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/listGetDisByAdmin")
	@ApiOperation(value = "远程教育记录", notes = "查询同级或同级以下记录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
			@ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
			@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
			@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
			@ApiImplicitParam(name = "searchDName", value = "会议名称", paramType = "query") })
	public JsonQueryObject<Distancelearning> getDistancelearningByAdminList(@ApiIgnore DistancelearningQuery query,
			HttpServletRequest request, Model model) {
		// 是否包含下级单位
		String u = LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
		query.setSearchScopeCode(u);
		LoginAuthUser user = LoginAuthUser.getUser(request);
		query.setSearchUserID(user.getEntityID());
		if (query.getSearchYear() == null || "".equals(query.getSearchYear())) {
			query.setSearchYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		try {
			List<Distancelearning> list = distancelearningService.getDisListMobile(query);
			if (null != list && list.size() > 0) {
				for (Distancelearning d : list) {
					Map params = new HashMap();
					params.put("groupId", d.getDistancelearningID());
					String resultList = remoteCallService.getForObject("fileListHandler", String.class, params);
					JSONObject json = JSONObject.parseObject(resultList).getJSONObject("data");
					JSONArray jsonList = json.getJSONArray("resultList");
					List<AttachementBean> ab = jsonList.toJavaList(AttachementBean.class);
					for (AttachementBean att : ab) {
						att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL + att.getAttachid());
						if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
							att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
						}else {
							att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
						}
					}
					d.setFileList(ab);

					List<DistancelearningUser> headList = distancelearningService
							.getHeadList(d.getDistancelearningID());
					if (!headList.isEmpty()) {
						d.setHeadList(headList);
					}
					List<DistancelearningUser> leaveList = distancelearningService
							.getLeaveList(d.getDistancelearningID());
					if (!leaveList.isEmpty()) {
						d.setLeaveList(leaveList);
					}
					List<DistancelearningUser> singList = distancelearningService
							.getSingList(d.getDistancelearningID());
					if (!singList.isEmpty()) {
						d.setSingList(singList);
					}
					List<DistancelearningUser> defaultList = distancelearningService
							.getDefaultList(d.getDistancelearningID());
					if (!defaultList.isEmpty()) {
						d.setDefaultList(defaultList);
					}
					List<String> courseIDs = distancelearningService.getAllCourseIds(d.getDistancelearningID());
					if (!courseIDs.isEmpty()) {
						d.setCourseCount(courseIDs.size());
					}

				}
			}
			query.setResultList(list);
			model.addAttribute("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "失败");
		}
		return new JsonQueryObject<>(query);
	}

	/**
	 * 根据支部id查询远程教育
	 * 
	 * @date 2018年6月22日 下午4:33:00
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/findDisListByOrgId")
	@ApiOperation(value = "根据支部id查询", notes = "根据支部id查询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
			@ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
			@ApiImplicitParam(name = "searchOrganizationId", value = "支部id", paramType = "query"),
			@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
			@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
			@ApiImplicitParam(name = "searchDName", value = "会议名称", paramType = "query") })
	public JsonQueryObject<Distancelearning> getDisListByOrgId(@ApiIgnore DistancelearningQuery query,
			HttpServletRequest request, Model model) {
		LoginAuthUser user = LoginAuthUser.getUser(request);
		query.setSearchUserID(user.getEntityID());
		if (query.getSearchYear() == null || "".equals(query.getSearchYear())) {
			query.setSearchYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		try {
			List<Distancelearning> list = distancelearningService.getDisListByOrgId(query);
			if (null != list && list.size() > 0) {
				for (Distancelearning d : list) {
					Map params = new HashMap();
					params.put("groupId", d.getDistancelearningID());
					String resultList = remoteCallService.getForObject("fileListHandler", String.class, params);
					JSONObject json = JSONObject.parseObject(resultList).getJSONObject("data");
					JSONArray jsonList = json.getJSONArray("resultList");
					List<AttachementBean> ab = jsonList.toJavaList(AttachementBean.class);
					for (AttachementBean att : ab) {
						att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL + att.getAttachid());
						if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
							att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
						}else {
							att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
						}
					}
					d.setFileList(ab);
				}
			}
			query.setResultList(list);
			model.addAttribute("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "失败");
		}
		return new JsonQueryObject<>(query);
	}

	/**
	 * 新增远程教育
	 * 
	 * @date 2018年6月22日 下午4:32:44
	 * @author hanxiangyu
	 * @param obj
	 * @param request
	 * @return
	 */
	@PostMapping
	@ApiOperation(value = "新增远程教育", notes = "新增远程教育记录")
	public void addDistancelearning(Distancelearning obj, HttpServletRequest request, HttpServletResponse response) {
		LoginAuthUser u = LoginAuthUser.getUser(request);
		obj.setUserID(u.getEntityID());// 发布人id
		obj.setUserName(u.getName());// 发布人姓名
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if (null != obj.getBeginDate() && !"".equals(obj.getBeginDate())) {
				Date beginTime = sdf.parse(obj.getBeginDate());
				// 设置当前年份
				String year = String.valueOf(DateUtil.getYear(beginTime));
				obj.setYear(year);
				// 设置季度
				obj.setQuarter(DateUtil.getSeason(beginTime));
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (obj.getPublishState() != null && obj.getPublishState() == 1) {
			obj.setPublishDate(new Date());
		}
		if (!PropertyUtil.objectNotEmpty(obj.getOrganizationId())) {
			obj.setOrganizationId(conferenceService.getOrgIdByUserId(u.getEntityID()));
		}
		// 会议标签
		if (obj.getDistancelearningTypes() != null && obj.getDistancelearningTypes().length > 0) {
			obj.setDistancelearningType(StringUtils.join(obj.getDistancelearningTypes(), ","));
		}
		obj.setActiveState(DistancelearningQuery.ACTIVESTATE_YES);// 默认启用
		if (obj.getPublishState() == null) {
			obj.setPublishState(DistancelearningQuery.PUBLISHSTATE_NO);// 默认未发布
		}
		if (obj.getPublishState() != null && obj.getPublishState() == 1) {
			// 发布时间
			obj.setPublishDate(new Date());
		}
		obj.setCreateDate(new Date());

		// 生成直播间id
		obj.setLiveId(distancelearningService.getMaxLiveId());
		distancelearningService.addDistancelearning(obj);
		try {
			if (obj.getUserIDs() != null && obj.getUserIDs().length > 0) {
				distancelearningService.addDistancelearningUser(obj);
			}
			if (obj.getCourseIDs() != null && obj.getCourseIDs().length > 0) {
				distancelearningService.addDistancelearningCourse(obj);
			}
			if ("1".equals(obj.getIsSend()) && obj.getPublishState().intValue() == 1) {
				if (!noticeService.sendDisNotice(obj, NoticeQuery.NOTICE_ADD)) {
					PrintUtil.printMsg(response, false, "会议通知发送失败");
				}
			}
			PrintUtil.printMsg(response, true, "会议新增成功!");
		} catch (Exception e) {
			e.printStackTrace();
			PrintUtil.printMsg(response, false, "会议新增失败!");
		}
	}

	/**
	 * 查询远程教育
	 * 
	 * @date 2018年6月22日 下午4:33:00
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@GetMapping
	@ApiOperation(value = "远程教育记录", notes = "查询出自己创建及选择自己作为出席人的远程教育")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
			@ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
			@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
			@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query") })
	public JsonQueryObject<Distancelearning> getDistancelearningList(@ApiIgnore DistancelearningQuery query,
			HttpServletRequest request, Model model) {
		LoginAuthUser user = LoginAuthUser.getUser(request);
		query.setSearchUserID(user.getEntityID());// 发布人id
		if (query.getSearchYear() == null || "".equals(query.getSearchYear())) {
			query.setSearchYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		try {
			List<Distancelearning> list = distancelearningService.getDistancelearningList(query);
			if (null != list && list.size() > 0) {
				for (Distancelearning d : list) {
					Map params = new HashMap();
					params.put("groupId", d.getDistancelearningID());
					String resultList = remoteCallService.getForObject("fileListHandler", String.class, params);
					JSONObject json = JSONObject.parseObject(resultList).getJSONObject("data");
					JSONArray jsonList = json.getJSONArray("resultList");
					List<AttachementBean> ab = jsonList.toJavaList(AttachementBean.class);
					for (AttachementBean att : ab) {
						att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL + att.getAttachid());
						if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
							att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
						}else {
							att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
						}
					}
					d.setFileList(ab);

					List<DistancelearningUser> headList = distancelearningService
							.getHeadList(d.getDistancelearningID());
					if (!headList.isEmpty()) {
						d.setHeadList(headList);
					}
					List<DistancelearningUser> leaveList = distancelearningService
							.getLeaveList(d.getDistancelearningID());
					if (!leaveList.isEmpty()) {
						d.setLeaveList(leaveList);
					}
					List<DistancelearningUser> singList = distancelearningService
							.getSingList(d.getDistancelearningID());
					if (!singList.isEmpty()) {
						d.setSingList(singList);
					}
					List<DistancelearningUser> defaultList = distancelearningService
							.getDefaultList(d.getDistancelearningID());
					if (!defaultList.isEmpty()) {
						d.setDefaultList(defaultList);
					}
					List<String> courseIDs = distancelearningService.getAllCourseIds(d.getDistancelearningID());
					if (!courseIDs.isEmpty()) {
						d.setCourseCount(courseIDs.size());
					}
				}
			}
			query.setResultList(list);
			model.addAttribute("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "失败");
		}
		return new JsonQueryObject<>(query);
	}

	/**
	 * 查询远程教育
	 * 
	 * @date 2018年6月22日 下午4:33:00
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/listGetDisStat")
	@ApiOperation(value = "远程教育记录", notes = "查询出自己的同级支部")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
			@ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
			@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
			@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query") })
	public JsonQueryObject<Distancelearning> getDisStatList(@ApiIgnore DistancelearningQuery query,
			HttpServletRequest request, Model model) {
		String u = LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request); // 前台获取code
		query.setSearchScopeCode(u);
		// 设置当前年份
		String year = String.valueOf(DateUtil.getYear(new Date()));
		query.setSearchYear(year);
		try {
			List<Distancelearning> list = distancelearningService.getDisStatList(query);
			if (null != list && list.size() > 0) {
				for (Distancelearning d : list) {
					Map params = new HashMap();
					params.put("groupId", d.getDistancelearningID());
					String resultList = remoteCallService.getForObject("fileListHandler", String.class, params);
					JSONObject json = JSONObject.parseObject(resultList).getJSONObject("data");
					JSONArray jsonList = json.getJSONArray("resultList");
					List<AttachementBean> ab = jsonList.toJavaList(AttachementBean.class);
					for (AttachementBean att : ab) {
						att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL + att.getAttachid());
						if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
							att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
						}else {
							att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
						}
					}
					d.setFileList(ab);
				}
			}
			query.setResultList(list);
			model.addAttribute("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "失败");
		}
		return new JsonQueryObject<>(query);
	}

	/**
	 * 查询远程教育
	 * 
	 * @date 2018年6月22日 下午4:33:00
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/listGetDisVisStat")
	@ApiOperation(value = "远程教育记录统计", notes = "查询出自己的同级支部")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
			@ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
			@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
			@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query") })
	public JsonQueryObject<Distancelearning> getDisVisStatList(@ApiIgnore DistancelearningQuery query,
			HttpServletRequest request, Model model) {
		String u = LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request); // 前台获取code
		query.setSearchScopeCode(u);
		// 设置当前年份
		if (query.getSearchYear() == null || "".equals(query.getSearchYear())) {
			String year = String.valueOf(DateUtil.getYear(new Date()));
			query.setSearchYear(year);
		}
		List<Distancelearning> list = distancelearningService.getDisVisStatList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}

	/**
	 * 获取已参加人员列表
	 * 
	 * @date 2018年6月22日 下午4:33:10
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/listGetJoinUser")
	@ApiOperation(value = "获取已参加会议出席人列表", notes = "出席人列表查询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchUserName", value = "用户姓名", paramType = "query"),
			@ApiImplicitParam(name = "searchDistancelearningID", value = "记录id", paramType = "query") })
	public JsonQueryObject<DistancelearningUser> getConferenceList(@ApiIgnore DistancelearningUserQuery query,
			HttpServletRequest request, Model model) {
		List<DistancelearningUser> userList = distancelearningService.getDistancelearningUserList(query);
		query.setResultList(userList);
		return new JsonQueryObject<>(query);
	}

	/**
	 * 获取已参加人员ids
	 * 
	 * @date 2018年6月22日 下午4:33:27
	 * @author hanxiangyu
	 * @param obj
	 * @param request
	 * @return
	 */
	@GetMapping("/getJoinUserIds")
	@ApiOperation(value = "获取已选为出席人ids", notes = "获取已选为出席人ids")
	public JsonSuccessObject<DistancelearningUser> getConferenceUserIds(Distancelearning obj,
			HttpServletRequest request) {
		List<String> userIDs = distancelearningService.getJoinUserIDs(obj.getDistancelearningID());
		// String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);//后台获取code
		String u = LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request); // 前台获取code
		DistancelearningUser du = new DistancelearningUser();
		String[] userIds = new String[userIDs.size()];
		userIDs.toArray(userIds);
		du.setUserIDs(userIds);
		du.setScope(u);
		JsonSuccessObject<DistancelearningUser> returnResult = new JsonSuccessObject<DistancelearningUser>(du);
		return returnResult;
	}

	/**
	 * 获取会议详情
	 * 
	 * @date 2018年6月22日 下午4:33:48
	 * @author hanxiangyu
	 * @param obj
	 * @param request
	 * @return
	 */
	@GetMapping("/getDistanceByID")
	@ApiOperation(value = "获取远程教育会议详情", notes = "获取远程教育会议详情")
	public JsonSuccessObject<Distancelearning> GetDistanceByID(Distancelearning obj, HttpServletRequest request) {
		LoginAuthUser user = LoginAuthUser.getUser(request);
		obj.setUserID(user.getEntityID());
		Distancelearning distaance = distancelearningService.getDistaanceByID(obj);
		Map params = new HashMap();
		params.put("groupId", distaance.getDistancelearningID());
		String resultList = remoteCallService.getForObject("fileListHandler", String.class, params);
		JSONObject json = JSONObject.parseObject(resultList).getJSONObject("data");
		JSONArray jsonList = json.getJSONArray("resultList");
		List<AttachementBean> ab = jsonList.toJavaList(AttachementBean.class);
		for (AttachementBean att : ab) {
			att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL + att.getAttachid());
			if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
				att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
			}else {
				att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
			}
		}
		distaance.setFileList(ab);
		List<DistancelearningUser> headList = distancelearningService.getHeadList(obj.getDistancelearningID());
		if (!headList.isEmpty()) {
			distaance.setHeadList(headList);
		}
		List<DistancelearningUser> leaveList = distancelearningService.getLeaveList(obj.getDistancelearningID());
		if (!leaveList.isEmpty()) {
			distaance.setLeaveList(leaveList);
		}
		List<DistancelearningUser> singList = distancelearningService.getSingList(obj.getDistancelearningID());
		if (!singList.isEmpty()) {
			distaance.setSingList(singList);
		}
		List<DistancelearningUser> defaultList = distancelearningService.getDefaultList(obj.getDistancelearningID());
		if (!defaultList.isEmpty()) {
			distaance.setDefaultList(defaultList);
		}
		List<String> courseIDs = distancelearningService.getAllCourseIds(obj.getDistancelearningID());
		if (!courseIDs.isEmpty()) {
			distaance.setCourseCount(courseIDs.size());
		}
		JsonSuccessObject<Distancelearning> returnResult = new JsonSuccessObject<Distancelearning>(distaance);
		return returnResult;
	}

	/**
	 * 更新会议
	 * 
	 * @date 2018年6月22日 下午4:33:59
	 * @author hanxiangyu
	 * @param obj
	 * @param request
	 * @return
	 */
	@PutMapping
	@ApiOperation(value = "更新会议记录", notes = "远程教育更新")
	public void updateDistancelearning(Distancelearning obj, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 会议标签
		if (obj.getDistancelearningTypes() != null && obj.getDistancelearningTypes().length > 0) {
			obj.setDistancelearningType(StringUtils.join(obj.getDistancelearningTypes(), ","));
		}
		try {
			if (null != obj.getBeginDate() && !"".equals(obj.getBeginDate())) {
				Date beginTime = sdf.parse(obj.getBeginDate());
				// 设置当前年份
				String year = String.valueOf(DateUtil.getYear(beginTime));
				obj.setYear(year);
				// 设置季度
				obj.setQuarter(DateUtil.getSeason(beginTime));
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}

		if (obj.getPublishState() != null && obj.getPublishState() == 1) {
			// 发布时间
			obj.setPublishDate(new Date());
		}
		// 更新直播间id
		// obj.setLiveId(distancelearningService.getMaxLiveId());

		try {
			distancelearningService.updateDistancelearning(obj);
			Distancelearning distancelearning = distancelearningService.getDisByID(obj.getDistancelearningID());
			if ("1".equals(distancelearning.getIsSend()) && distancelearning.getPublishState().intValue() == DistancelearningQuery.PUBLISHSTATE_YES) {
				List<String> userIDs = distancelearningService.getJoinUserIDs(obj.getDistancelearningID());
				if (!userIDs.isEmpty()) {
					String[] iDs = new String[userIDs.size()];
					userIDs.toArray(iDs);// list-->数组
					distancelearning.setUserIDs(iDs);
					if (!noticeService.sendDisNotice(distancelearning, NoticeQuery.NOTICE_UPDATE)) {
						PrintUtil.printMsg(response, false, "修改会议发送通知失败!");
					}
				}
			}
			PrintUtil.printMsg(response, true, "会议更新成功!");
		} catch (Exception e) {
			e.printStackTrace();
			PrintUtil.printMsg(response, false, "会议更新失败!");
		}
	}

	/**
	 * @date 2018年6月25日 上午9:42:44
	 * @param obj
	 * @param request
	 * @return
	 */
	@PostMapping("/publishDistancelearning")
	@ApiOperation(value = "会议发布撤销操作", notes = "远程教育会议发布撤销操作")
	public void publishDistancelearning(Distancelearning obj, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		if (obj.getPublishState().intValue() == 1) {
			obj.setPublishDate(new Date());
			Distancelearning distancelearning = distancelearningService.getDisByID(obj.getDistancelearningID());
			distancelearning.setPublishState(obj.getPublishState());
			List<String> userIDs = distancelearningService.getJoinUserIDs(obj.getDistancelearningID());
			if (!userIDs.isEmpty()) {
				String[] iDs = new String[userIDs.size()];
				userIDs.toArray(iDs);// list-->数组
				distancelearning.setUserIDs(iDs);
				if (!noticeService.sendDisNotice(distancelearning, NoticeQuery.NOTICE_UPDATE)) {
					PrintUtil.printMsg(response, false, "会议发布时发送通知失败!");
				}
			}
		} else if (obj.getPublishState().intValue() == 2) {
			Distancelearning distancelearning = distancelearningService.getDisByID(obj.getDistancelearningID());
			distancelearning.setPublishState(obj.getPublishState());
			List<String> userIDs = distancelearningService.getJoinUserIDs(obj.getDistancelearningID());
			if (!userIDs.isEmpty()) {
				String[] iDs = new String[userIDs.size()];
				userIDs.toArray(iDs);// list-->数组
				distancelearning.setUserIDs(iDs);
				if (!noticeService.sendDisNotice(distancelearning, NoticeQuery.NOTICE_CANCEL)) {
					PrintUtil.printMsg(response, false, "会议取消时发送通知失败!");
				}
			}
		}
		if (obj.getPublishState().intValue() == 1) {
			if (distancelearningService.publishDistancelearning(obj)) {
				PrintUtil.printMsg(response, true, "会议发布成功!");
			} else {
				PrintUtil.printMsg(response, false, "会议发布失败!");
			}
		} else {
			if (distancelearningService.publishDistancelearning(obj)) {
				PrintUtil.printMsg(response, true, "会议取消发布成功!");
			} else {
				PrintUtil.printMsg(response, false, "会议取消发布失败!");
			}
		}
	}

	/**
	 * @date 2018年6月25日 上午9:42:55
	 * @param obj
	 * @param request
	 * @return
	 */
	@GetMapping("/getCourseIds")
	@ApiOperation(value = "获取已选课件ids", notes = "获取已选课件ids")
	public JsonSuccessObject<List<String>> getConferenceUserIds(DistancelearningCourse obj,
			HttpServletRequest request) {
		List<String> courseIDs = distancelearningService.getAllCourseIds(obj.getDistancelearningID());
		JsonSuccessObject<List<String>> returnResult = new JsonSuccessObject<List<String>>(courseIDs);
		return returnResult;
	}

	/**
	 * @date 2018年6月25日 上午9:43:03
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/listGetCourse")
	@ApiOperation(value = "获取已关联课件列表", notes = "课件列表查询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchDistancelearningId", value = "会议id", paramType = "query") })
	public JsonQueryObject<DistancelearningCourse> getConferenceList(@ApiIgnore DistancelearningCourseQuery query,
			HttpServletRequest request, Model model) {
		List<DistancelearningCourse> courseList = distancelearningService.getDistancelearningCourseList(query);
		query.setResultList(courseList);
		return new JsonQueryObject<>(query);
	}

	/**
	 * @date 2018年6月25日 上午9:43:14
	 * @param obj
	 * @param request
	 * @return
	 */
//	@PostMapping("/receipt")
//	@ApiOperation(value = "回执/请假操作", notes = "远程教育会议回执")
//	public void disReceipt(DistancelearningUser obj, HttpServletRequest request, HttpServletResponse response,
//			Model model) {
//		LoginAuthUser user = LoginAuthUser.getUser(request);
//		obj.setUserID(user.getEntityID());
//		obj.setReceiptDate(new Date());
//		distancelearningService.disReceipt(obj);
//		if (distancelearningService.disReceipt(obj)) {
//			if (obj.getReceiptType().intValue() == 3) {
//				PrintUtil.printMsg(response, true, "请假成功!");
//			} else {
//				PrintUtil.printMsg(response, true, "操作成功!");
//			}
//		} else {
//			PrintUtil.printMsg(response, false, "操作失败,请联系管理员!");
//		}
//
//	}

	@PostMapping("/addAttendance")
	@ApiOperation(value = "考勤记录", notes = "对远程教育的考勤记录")
	public void addAttendance(DistancelearningAttendance obj, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		obj.setAttendanceDate(new Date());
		if (obj.getAttendanceType() == null) {
			obj.setAttendanceType(DistancelearningQuery.STATUS_YQ);
		}
		LoginAuthUser u = LoginAuthUser.getUser(request);
		if (obj.getUserIDs() == null || obj.getUserIDs().length <= 0) {
			String[] userID = { u.getEntityID() };
			obj.setUserIDs(userID);
		}
		//判断是否存在此登陆人
		Distancelearning dis = new Distancelearning();
		dis.setDistancelearningID(obj.getDistancelearningID());
		dis.setUserIDs(obj.getUserIDs());
		List<DistancelearningUser> userList = distancelearningService.getExistJoinUserList(dis);
		if (PropertyUtil.objectNotEmpty(userList)) {
			// 确定是否存在考勤记录
			if (PropertyUtil.objectNotEmpty(obj.getUserIDs()) && obj.getUserIDs().length == 1) {//扫描二维码签到
				List<DistancelearningAttendance> userIdsList = distancelearningService.getDisAttendanceByUserIdsList(obj);
				if (PropertyUtil.objectNotEmpty(userIdsList)) {
					PrintUtil.printMsg(response, false, "已经进行过签到，请勿重复签到!");
				}else {
					if (PropertyUtil.objectNotEmpty(obj.getViaTime())) {
						Date date = DateUtil.strToDate(obj.getViaTime());
						long minute = DateUtil.getMinute(new Date(), date);
						if (minute >= 5) {
							PrintUtil.printMsg(response, false, "二维码已过期!");
						} else {
							try {
								this.signLogic(userList, obj, 1);
								PrintUtil.printMsg(response, true, "签到成功!");
							} catch (Exception e) {
								e.printStackTrace();
								PrintUtil.printMsg(response, false, "签到失败!");
							}
						}
					}else {
						try {
							this.signLogic(userList, obj, 1);
							PrintUtil.printMsg(response, true, "签到成功!");
						} catch (Exception e) {
							e.printStackTrace();
							PrintUtil.printMsg(response, false, "签到失败!");
						}
					}
				}
			}else {//点名签到
				try {
					this.signLogic(userList, obj, 2);
					PrintUtil.printMsg(response, true, "签到成功!");
				} catch (Exception e) {
					e.printStackTrace();
					PrintUtil.printMsg(response, false, "签到失败!");
				}
			}
		}else {
			PrintUtil.printMsg(response, false, "您未参加此会议,不能进行签到!");
		}
		
	}

	public void signLogic(List<DistancelearningUser> userList,DistancelearningAttendance obj,Integer i) throws Exception {
		for (String userID : obj.getUserIDs()) {
			obj.setUserID(userID);
			if (i.intValue() == 1) {
				distancelearningService.addDisAttendance(obj);
				// 执行考勤时更新一下回执表
				DistancelearningUser disUser = new DistancelearningUser();
				disUser.setUserID(obj.getUserID());
				disUser.setDistancelearningID(obj.getDistancelearningID());
				disUser.setReceiptType(DistancelearningQuery.STATUS_NOQJ);
				distancelearningService.disReceipt(disUser);
			}else {
				List<DistancelearningAttendance> attendanceList = distancelearningService.getDisAttendance(obj);
				// 只存在一条考勤记录时
				if (attendanceList.isEmpty()) {// 判断是否有考勤记录如不存在考勤记录更新会议表考勤数+1
					distancelearningService.addDisAttendance(obj);
				} else {
					distancelearningService.updateDisAttendance(obj);
				}
				// 执行考勤时更新一下回执表
				DistancelearningUser disUser = new DistancelearningUser();
				disUser.setUserID(obj.getUserID());
				disUser.setDistancelearningID(obj.getDistancelearningID());
				disUser.setReceiptType(DistancelearningQuery.STATUS_NOQJ);
				distancelearningService.disReceipt(disUser);
			}
		}
	}
	
	
	
	@PutMapping("/updateReceipt")
	@ApiOperation(value = "回执操作/请假", notes = "对远程教育的回执/请假操作")
	public void updateReceipt(DistancelearningUser obj, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		LoginAuthUser u = LoginAuthUser.getUser(request);
		if (!PropertyUtil.objectNotEmpty(obj.getUserID())) {
			obj.setUserID(u.getEntityID());
		}
		List<DistancelearningUser> userList = distancelearningService.getJoinUserByUserIds(obj);
		if (PropertyUtil.objectNotEmpty(userList)) {
			if (PropertyUtil.objectNotEmpty(userList.get(0).getReceiptType()) && userList.get(0).getReceiptType().intValue() == DistancelearningQuery.STATUS_QJ) {
				PrintUtil.printMsg(response, false, "您已进行过请假，请勿重复进行请假!");
			}else {
				// 回执时间
				obj.setReceiptDate(new Date());
				// 确定是否存在考勤记录
				DistancelearningAttendance disAtt = new DistancelearningAttendance();
				disAtt.setUserID(obj.getUserID());
				disAtt.setDistancelearningID(obj.getDistancelearningID());
				List<DistancelearningAttendance> attendanceList = distancelearningService.getDisAttendance(disAtt);
				if (!attendanceList.isEmpty()) {
					distancelearningService.deleteDisAttendance(disAtt);
				}
				Boolean bl = distancelearningService.disReceipt(obj);
				if (bl) {
					if (obj.getReceiptType().intValue() == 3) {
						PrintUtil.printMsg(response, true, "请假成功!");
					} else {
						PrintUtil.printMsg(response, true, "操作成功!");
					}
				}else {
					if (obj.getReceiptType().intValue() == 3) {
						PrintUtil.printMsg(response, false, "请假失败!");
					} else {
						PrintUtil.printMsg(response, false, "操作失败!");
					}
				}
			}
		}else {
			if (obj.getReceiptType().intValue() == 3) {
				PrintUtil.printMsg(response, false, "您未参加此会议,不能进行请假!");
			} else {
				PrintUtil.printMsg(response, false, "您未参加此会议,不能进行回执!");
			}
		}
	}

	@RequestMapping("/updateLiveStatus")
	@ApiOperation(value = "更新直播信息", notes = "对远程教育直播信息操作")
	public void updateLiveStatus(Distancelearning obj, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {
			// Distancelearning dis =
			// distancelearningService.getDisByLiveId(obj.getLiveId());
			// if (dis != null && dis.getDistancelearningID() != null) {
			// obj.setDistancelearningID(dis.getDistancelearningID());
			// }
			distancelearningService.updateLiveStatus(obj);
			PrintUtil.printMsg(response, true, "更新成功!");
		} catch (Exception e) {
			e.printStackTrace();
			PrintUtil.printMsg(response, false, "操作失败,请联系管理员!");
		}
	}

	@RequestMapping("/updateDisById")
	@ApiOperation(value = "启用/未启用", notes = "启用/未启用")
	public void updateDisById(Distancelearning obj, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {
			distancelearningService.updateDisById(obj);
			PrintUtil.printMsg(response, true, "成功!");
		} catch (Exception e) {
			e.printStackTrace();
			PrintUtil.printMsg(response, false, "失败!");
		}
	}

	/**
	 * 查询远程教育录播记录
	 * 
	 * @date 2018年6月22日 下午4:33:00
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getLBList")
	@ApiOperation(value = "远程教育录播记录", notes = "查询已参加的和创建的记录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
			@ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
			@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
			@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
			@ApiImplicitParam(name = "searchDName", value = "会议名称", paramType = "query"),
			@ApiImplicitParam(name = "searchParentId", value = "管理范围", paramType = "query"),
			@ApiImplicitParam(name = "searchIsInclude", value = "是否包含下级单位", paramType = "query") })
	public JsonQueryObject<Distancelearning> getLBList(@ApiIgnore DistancelearningQuery query,
			HttpServletRequest request, Model model) {

		if (query.getSearchUserID() == null || "".equals(query.getSearchUserID())) {
			LoginAuthUser user = LoginAuthUser.getUser(request);
			query.setSearchUserID(user.getEntityID());
		}
		List<Distancelearning> list = distancelearningService.getLBList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}

	/**
	 * 查询远程教育录播记录
	 * 
	 * @date 2018年6月22日 下午4:33:00
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getLBListByAdmin")
	@ApiOperation(value = "远程教育录播记录", notes = "查询同级和同级以下记录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
			@ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
			@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
			@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
			@ApiImplicitParam(name = "searchDName", value = "会议名称", paramType = "query"),
			@ApiImplicitParam(name = "searchParentId", value = "管理范围", paramType = "query"),
			@ApiImplicitParam(name = "searchIsInclude", value = "是否包含下级单位", paramType = "query") })
	public JsonQueryObject<Distancelearning> getLBListByAdmin(@ApiIgnore DistancelearningQuery query,
			HttpServletRequest request, Model model) {
		// 是否包含下级单位
		String u = LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);// 后台获取code
		query.setSearchScopeCode(u);
		List<Distancelearning> list = distancelearningService.getLBListByAdmin(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}

	@PostMapping("/updateDisImg")
	@ApiOperation(value = "更新封面图", notes = "更新封面图")
	public void updateDisImg(Distancelearning obj, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {
			distancelearningService.updateDisById(obj);
			PrintUtil.printMsg(response, true, "成功!");
		} catch (Exception e) {
			e.printStackTrace();
			PrintUtil.printMsg(response, false, "失败!");
		}
	}

	@PostMapping("/startAndEndDis")
	@ApiOperation(value = "删除会议", notes = "删除三会一课")
	public void startAndEndDis(DistancelearningBean obj, HttpServletResponse response) {
		if (distancelearningService.startAndEndDis(obj)) {
			PrintUtil.printMsg(response, true, "删除成功!");
		} else {
			PrintUtil.printMsg(response, false, "删除失败");
		}
	}

	// public void addDisNotifyRecord(Distancelearning obj,HttpServletRequest
	// request,HttpServletResponse response,Model model) {
	// Notice notice = new Notice();
	// String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	// notice.setUserID(obj.getUserID());//发布人id
	// notice.setUserName(obj.getUserName());
	// notice.setLastModifyTime(date);
	// notice.setActiveState(AddressBookGroupQuery.ACTIVESTATE_YES);
	// notice.setPublishState(AddressBookGroupQuery.PUBLISH_YES);
	// noticeService.addNotice(notice);
	//
	// }
	//
	// //添加关联关系
	// public void sendNotice(Notice notice) {
	// //添加关联关系记录
	// String[] userIDs=notice.getUserIDs();
	// if(null!=userIDs && userIDs.length>0) {
	// NoticeUserQuery query=new NoticeUserQuery();
	// query.setSearchNoticeID(notice.getNoticeID());
	// List<NoticeUser> userList=noticeUserService.getNoticeUserList(query);
	// if(null!=userList && userList.size()>0) {
	// //删除关联关系
	// noticeUserService.deleteNoticeUser(notice.getNoticeID());
	// }
	// for(String userID:userIDs) {
	// NoticeUser user=new NoticeUser();
	// user.setNoticeID(notice.getNoticeID());
	// user.setUserID(userID);
	// noticeUserService.addNoticeUser(user);
	// }
	// }
	//
	// }

}
